import argparse
import ipaddress
import signal
import time

from p2p import ecies

from .config import DEFAULT_PORT
from .core import Connection

running = True


def sig(*_):
    global running
    running = False
    print()


def main():
    parser = argparse.ArgumentParser(description='Ethereum network deviant nodes finder')
    parser.add_argument("ip", help="node ip", type=ipaddress.ip_address)
    parser.add_argument("-p", "--port", help="targeted port", type=int)
    parser.add_argument("-i", "--interval", help="time between each ping",
                        type=float, default=1.5, metavar="SECS")
    parser.add_argument("-q", "--quiet", help="disable stdout messages", action="store_true")
    parser.add_argument("-s", "--show-ids", help="show the pinger id", action="store_true")
    args = parser.parse_args()

    if args.ip is not None:

        port = args.port if args.port is not None else DEFAULT_PORT

        if not args.quiet:
            print("Initiating connection...")

        private_key = ecies.generate_privkey()
        conn = Connection(private_key=private_key, quiet=args.quiet, show=args.show_ids)
        conn.open()

        signal.signal(signal.SIGINT, sig)
        if not args.quiet:
            print(f"Noot-nooting {args.ip} on port {port}")
        while running:
            conn.ping(str(args.ip), port, port)
            time.sleep(args.interval)
        conn.close()
        print(conn.ping_count, "pings sent")
        print(conn.pong_count, "pongs received")
        print(conn.ping_count - conn.pong_count, "unanswered pings",
              f"({round(((conn.ping_count - conn.pong_count) / conn.ping_count) * 100, 2)}%)")
